package a66weding.com.jiehuntong.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;

import org.xutils.x;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import a66weding.com.jiehuntong.MainActivity;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.me.LiuChengActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MarriageProposalBean;
import a66weding.com.jiehuntong.beans.MeMarriedDayBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.UpLoadImage;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.common.utils.DateUtils;
import a66weding.com.jiehuntong.common.utils.FileUtil;
import a66weding.com.jiehuntong.common.utils.SharesUtils;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.common.utils.dataselect.DataSelectUtil;
import a66weding.com.jiehuntong.common.utils.uploadimage.UpLoadUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.inner.DataCallBack;
import a66weding.com.jiehuntong.pager.Diy_YusuanPager;
import a66weding.com.jiehuntong.widgets.CircularImage;

/**
 * Created by admin on 2016/6/14.
 */
//Activity
public class Diy_HeadActivity extends Activity implements View.OnClickListener, UpLoadUtil.ResultCallBack, OnNetResultListener, DataCallBack {

    private RelativeLayout rl_touxiang, rl_yusuan, rl_hunqi, rl_addliucheng, rl_delliucheng;
    private Button photoBtn, cameraBtn, quxiaoBtn;
    public Dialog dialog;
    private CircularImage userPhoto;
    private TextView tv_hunqi;
    private String birthday;
    private TextView head_title;
    private Bitmap bitmap;
    //头像的名字
    public static String HEAD_PHOTO_NAME = "head_image.jpg";
    //获得文件
    private File file;
    //预算金额;
    private TextView budget;
    private String marray_budget;
    private String money;
    //婚期
    public static String WEDDING = "Wedding";
    private String wedding_day;
    private TextView title_tv;
    private List<MarriageProposalBean.DataBean> dataBeenList;
    private String phone;
    private static final int PERMISSION_SDCARD = 4;
    private static final int PERMISSION_CAMERA=5;
    private static final int TAKE_PHOTO=2;
    //返回键
    private LinearLayout llay_header_back;
    //返回字体
    private TextView tv_header_backcontent;
    //隐藏的内容;
    private TextView tv_header_function;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diy_engaged_a);
        /**
         * getResources().getColor(R.color.tab_top_bg)
         */
        dataBeenList = (List<MarriageProposalBean.DataBean>) getIntent().getSerializableExtra("flag");
        initView();
        initData();
    }

    private void initView() {
        tv_header_function = (TextView) findViewById(R.id.tv_header_function);
        tv_header_function.setVisibility(View.INVISIBLE);
        tv_header_backcontent = (TextView) findViewById(R.id.tv_header_backcontent);
        tv_header_backcontent.setText("返回");
        llay_header_back = (LinearLayout) findViewById(R.id.llay_header_back);
        llay_header_back.setOnClickListener(this);
        phone = DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_MobilePhone();
        userPhoto = (CircularImage) findViewById(R.id.cover_user_photo);
        if (DataWareHourse.getInstance().getmUser() != null) {
            x.image().bind(userPhoto, DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_TitlePhoto());
        }
        rl_delliucheng = (RelativeLayout) findViewById(R.id.relativelayout_delliucheng);
        rl_addliucheng = (RelativeLayout) findViewById(R.id.relativelayout_addliucheng);
        rl_touxiang = (RelativeLayout) findViewById(R.id.relativelayout_touxiang);
        rl_yusuan = (RelativeLayout) findViewById(R.id.relativelayout_yusuan);
        rl_hunqi = (RelativeLayout) findViewById(R.id.relativelayout_hunqi);
        tv_hunqi = (TextView) findViewById(R.id.textview_hunqi);
        rl_delliucheng.setOnClickListener(this);
        rl_addliucheng.setOnClickListener(this);
        rl_touxiang.setOnClickListener(this);
        rl_yusuan.setOnClickListener(this);
        rl_hunqi.setOnClickListener(this);
        //标题
        head_title = (TextView) findViewById(R.id.tv_header_title);
        //修改标题
        //保存
        budget = (TextView) findViewById(R.id.textview_yusuan);
        marray_budget = SharesUtils.getInstance(this).readXML(Diy_YusuanPager.MARRY_BUDGET);
//        wedding_day = SharesUtils.getInstance(this).readXML(WEDDING);
        wedding_day = DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_WeddingDate();

        if (marray_budget != null) {
            budget.setText(marray_budget);
        }
        if (wedding_day != null) {
            tv_hunqi.setText(wedding_day);
        }
        head_title.setVisibility(View.INVISIBLE);
    }

    private Set<String> set;

    private void initData() {
        if (dataBeenList != null) {
            getTitle(dataBeenList);
        }
    }

    private void getTitle(List<MarriageProposalBean.DataBean> data) {
        set = new HashSet<>();
        for (int i = 0; i < data.size(); i++) {
            set.add(data.get(i).getBookTitle());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.relativelayout_touxiang:
                showTouxiang();
                break;
            case R.id.relativelayout_yusuan:
                Intent intent = new Intent(this, Diy_YusuanPagerActivity.class);
                intent.putExtra("Diy_HeadActivity",budget.getText());
                startActivityForResult(intent, 4);
                break;
            case R.id.relativelayout_hunqi:
                DataSelectUtil.getInstance().showdatePopupWindow(v, this, this, 0);
                break;
            case R.id.relativelayout_addliucheng:
                Go2Add();
                break;
            case R.id.relativelayout_delliucheng:
                Go2Cut();
                break;
            case R.id.llay_header_back:
                finish();
                break;
        }
    }


    /**
     * 上传照片
     */
    public void showTouxiang() {
        View view = getLayoutInflater().inflate(R.layout.activity_tools_dialog_photo, null);
        photoBtn = (Button) view.findViewById(R.id.dialog_photo_button);
        cameraBtn = (Button) view.findViewById(R.id.dialog_camera_button);
        quxiaoBtn = (Button) view.findViewById(R.id.dialog_quxiao_button);

        photoBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showPhoto();
                dialog.dismiss();
            }
        });
        cameraBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCamera();
                dialog.dismiss();
            }

        });
        quxiaoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 拍照
     */
    public void showCamera() {
        /**
         * 下面这句还是老样子，调用快速拍照功能，至于为什么叫快速拍照，大家可以参考如下官方
         * 文档，you_sdk_path/docs/guide/topics/media/camera.html
         *
         */
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]
      {Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_SDCARD);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            file = new File(Environment.getExternalStorageDirectory(), "xiaoma.jpg");
            //下面这句指定调用相机拍照后的照片存储的路径
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
            startActivityForResult(intent, 2);
        }
    }

    /**
     *系统相册图库
     */
    private void showPhoto() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请MOUNT_UNMOUNT_FILESYSTEMS权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_CAMERA);
        }else{
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            //下面这句指定调用相机拍照后的照片存储的路径
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        doNext(requestCode, grantResults);
    }

    private void doNext(int requestCode, int[] grantResults) {
        if (requestCode == PERMISSION_CAMERA) {
            if (grantResults.length>0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                //下面这句指定调用相机拍照后的照片存储的路径
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, 1);

            } else {
                CUtils.showToast("请打开手机拍照权限后在操作");
            }
        }else if(requestCode ==PERMISSION_SDCARD){
            if(grantResults.length>0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                file = new File(Environment.getExternalStorageDirectory(), "xiaoma.jpg");
                //下面这句指定调用相机拍照后的照片存储的路径
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent, 2);
            }else{
                CUtils.showToast("请打开手机SD卡权限后在操作");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != 0){
            switch (requestCode) {
                // 如果是直接从相册获取
                case 1:
                    if (data != null) {
                        startPhotoZoom(data.getData());
                    }
                    break;
                // 如果是调用相机拍照时
                case 2:
                    File temp = new File(Environment.getExternalStorageDirectory() + "/xiaoma.jpg");
                    startPhotoZoom(Uri.fromFile(temp));
                    break;
                // 取得裁剪后的图片
                case 3:
                    /**
                     * 非空判断大家一定要验证，如果不验证的话，
                     * 在剪裁之后如果发现不满意，要重新裁剪，丢弃
                     */
                    if (data != null) {
                        setPicToView(data);
                    }
                    break;
                case 4:
                    //返回来的数据
                    if (data != null && Diy_YusuanPagerActivity.MARRY_BUDGET != null &&
                            data.getStringExtra(Diy_YusuanPagerActivity.MARRY_BUDGET) != null) {
                        money = data.getStringExtra(Diy_YusuanPagerActivity.MARRY_BUDGET);
                    }
                    if (money != null) {
                        budget.setText(money);
                    }
                    break;
                case 5:
                    finish();
                    break;
                default:
                    break;


            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            File saveFile = new File(FileUtil.getImgFile(this), HEAD_PHOTO_NAME);

            try {
                FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
                fileOutputStream.write(byteArray, 0, byteArray.length);
                fileOutputStream.flush();
                fileOutputStream.close();

            } catch (Exception e) {

                e.printStackTrace();
            }
            //上传服务器
            uploadfile(saveFile);
            userPhoto.setImageDrawable(drawable);

        }
    }


    public void back(View view) {
        CUtils.showToast("返回");
        Intent intent = new Intent();
        setResult(MainActivity.getResultCode, intent);
        finish();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Tools.dismissWaitDialog();
        }
    };

    /**
     * android上传文件到服务器
     *
     * @param file       需要上传的文件
     * @param RequestURL 请求的rul
     * @return 返回响应的内容
     */
    public String uploadFile(File file, String RequestURL) {
        String result = "";
        String BOUNDARY = UUID.randomUUID().toString();
        //边界标识 随机生成
        String PREFIX = "--", LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data"; //内容类型
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10 * 100000);
            conn.setConnectTimeout(10 * 100000);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST"); //请求方式
            conn.setRequestProperty("Charset", "utf-8");
            //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if (file != null) {
                /** * 当文件不为空，把文件包装并且上传 */
                OutputStream outputSteam = conn.getOutputStream();
                DataOutputStream dos = new DataOutputStream(outputSteam);
                StringBuffer sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\"" + LINE_END);
                sb.append("Content-Type: application/octet-stream; charset=utf-8" + LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = is.read(bytes)) != -1) {
                    dos.write(bytes, 0, len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();
                /**
                 * 获取响应码 200=成功
                 * 当响应成功，获取响应的流
                 */
                int res = conn.getResponseCode();
                if (res == 200) {
                    // 读取返回数据
                    StringBuffer strBuf = new StringBuffer();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        strBuf.append(line).append("\n");
                    }
                    result = strBuf.toString();
                    reader.close();
                    Tools.dismissWaitDialog();
                    return result;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * POST WeddingMobileApiSD/PostUpBookPicture?Token={Token}&mobileStr={mobileStr}&bookId={bookId}
     */
    private void uploadfile(final File saveFile) {
        Tools.showDialog(this);
        //图片上传地址
        //String phone = DataWareHourse.getInstance().getmUser().getData().get(0).getNvc_MobilePhone();
        String id = "" + DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id();
        final String url = Url.SURL + "/WeddingMobileApiSD/PostUpload?Token=00&mobileStr=" + phone + "&bookId=" + id;
        new Thread() {
            @Override
            public void run() {
                String result = uploadFile(saveFile, url);
                try {
                    Gson mgson = new Gson();
                    UpLoadImage upLoadImage = mgson.fromJson(result, UpLoadImage.class);
                    //更新内存



                    DataWareHourse.getInstance().getmUser().getData().get(0).setNvc_TitlePhoto(upLoadImage.getResult().getUrlField());
                    //更新本地缓存
                    CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, DataWareHourse.getInstance().getmUser());
                    handler.sendMessage(null);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    public void getResult(UpLoadImage upLoadImage) {

    }

    private void sendBroadCase() {
        Intent intent = new Intent();
        intent.setAction("aaa.bbb.ccc");
        sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * POST Wedding/Update_WeddingDate?Token={Token}&i_Id={i_Id}
     * 修改结婚书婚期
     */
    private void updataWeding() {
        Tools.showDialog(this);
        String url = UrlDealUtil.getRealUrl(RequestCode.UPDATE_WEDDINGDATE);
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("WeddingDate", birthday);
        HttpRequestBean requestBean1 = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, MeMarriedDayBean.class, RequestCode.UPDATE_WEDDINGDATE, paramsMap);
        HttpHandleUtil.executeCommonPost(this, requestBean1);
        /**
         * 保存距离结婚还有多少天;
         */
        SharesUtils.getInstance(this).writeXML("diy_which_day", "" + DateUtils.daysBetween(refFormatNowDate(), birthday));

    }

    /**
     * 获取当前时间;
     *
     * @return
     */
    public String refFormatNowDate() {
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
        return retStrFormatNowDate;
    }

    /**
     * POST Wedding/Update_WeddingBudget?Token={Token}&i_Id={i_Id}
     * 修改结婚预算
     */
    private void update_buget() {
        String url = UrlDealUtil.getRealUrl(RequestCode.UPDATE_WEDDINGBUDGET);
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("WeddingBudget", money);
        HttpRequestBean requestBean1 = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, CommonResultBean.class, RequestCode.UPDATE_WEDDINGDATE, paramsMap);
        HttpHandleUtil.executeCommonPost(this, requestBean1);
    }

    private CommonResultBean bean;

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Tools.dismissWaitDialog();
        Object data = sucessbean.getData();
        if (data instanceof CommonResultBean) {
            bean = (CommonResultBean) data;
            switch (bean.getResCode()) {
                case "0000":
                    CUtils.showToast("修改成功");
                    break;
            }
        }
        if(data instanceof MeMarriedDayBean) {
            MeMarriedDayBean marriedDayBean = (MeMarriedDayBean) data;
            if ("0000".equals(marriedDayBean.getResCode())) {
                CUtils.showToast("婚期修改成功");
                DataWareHourse.getInstance().getmUser().getData().get(0).setNvc_WeddingDate(birthday);
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {

    }

    @Override
    public void sendData(String time, int flag) {
        tv_hunqi.setText(time);
        birthday = time;
        SharesUtils.getInstance(Diy_HeadActivity.this).writeXML(WEDDING, birthday);
        updataWeding();
    }

    //增加流程
    private void Go2Add(){
        Intent intent = new Intent(this, LiuChengActivity.class);
        intent.putExtra("LiuChengActivity",1);
        startActivityForResult(intent,5);
    }

    //删除流程;
    private void Go2Cut(){
        Intent intent = new Intent(this, LiuChengActivity.class);
        intent.putExtra("LiuChengActivity",2);
        startActivityForResult(intent,5);
    }

}
